package cn.edu.zzuli;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Date: 2021/3/6 19:26
 * @Author: 绯色下午茶
 * @Description: 多个线程之间按顺序调用，实现A->B->C
 */
class ShareResource {
    private int number = 1; //1:A  2:b  3:C
    private Lock lock = new ReentrantLock();
    Condition condition1 = lock.newCondition();
    Condition condition2 = lock.newCondition();
    Condition condition3 = lock.newCondition();

    public void print5() {
        lock.lock();
        try {
            while (number != 1) {
                condition1.await();
            }
            for (int i = 0; i <= 4; i++) {
                System.out.println(Thread.currentThread().getName() + "   *** " +i);
            }
            number = 2;
            condition2.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void print10() {
        lock.lock();
        try {
            while (number != 2) {
                condition2.await();
            }
            for (int i = 0; i <= 9; i++) {
                System.out.println(Thread.currentThread().getName() + "   *** " + i);
            }
            number = 3;
            condition3.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void print15() {
        lock.lock();
        try {
            while (number != 3) {
                condition3.await();
            }
            for (int i = 0; i <= 14; i++) {
                System.out.println(Thread.currentThread().getName() + "   *** " + i);
            }
            number = 1;
            condition1.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}

public class ThreadOrderAccess {
    public static void main(String[] args) {
        System.out.println("111");
        ShareResource shareResource = new ShareResource();
        new Thread(() -> {
            for (int i = 0; i < 9; i++) {
                shareResource.print5();
            }

        }, "A").start();
        new Thread(() -> {
            for (int i = 0; i < 9; i++) {
                shareResource.print10();
            }
        }, "B").start();
        new Thread(() -> {
            for (int i = 0; i < 9; i++) {
                shareResource.print15();
            }
        }, "C").start();
    }
}
